package com.animal.controller;

import com.animal.common.Result;
import com.animal.entity.pojo.APet;
import com.animal.service.PetService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping("/pets")
public class PetController {
    @Autowired
    private PetService petService;

    //获取所有
    @GetMapping("/list")
    @ResponseBody
    public Result getAllPet(@RequestParam(required = false) String petName,
                            @RequestParam(required = false) String petType,
                            @RequestParam(required = false) Integer status,
                            @RequestParam Integer pageNo,
                            @RequestParam Integer pageSize) {
        PageHelper.startPage(pageNo, pageSize);
        System.out.println("status = " + status);
        List allPet = petService.getAllPet(petName, petType, status);
        PageInfo<Object> objectPageInfo = new PageInfo<>(allPet);
        if (allPet != null) {
            return Result.success(objectPageInfo);
        } else {
            return Result.error();
        }
    }


    /**
     * 添加
     * @param aPet
     * @return
     */
    @PostMapping("/add")
    @ResponseBody
    public Result add(@RequestBody APet aPet) {
        int add = petService.add(aPet);
        if (add > 0) {
            return Result.success();
        }
        return Result.error();
    }

    //批量删除
    @PostMapping("/del")
    @ResponseBody
    public Result dels(@RequestBody List<Integer> ids) {
        System.out.println("ids = " + ids);
        int i = petService.delByIds(ids);
        if (i < 0) {
            return Result.error();
        }
        return Result.success();
    }

    @PostMapping("/getPetById/{id}")
    @ResponseBody
    public Result getPetById(@PathVariable Integer id) {
        APet petById = petService.getPetById(id);
        if (petById != null) {
            return Result.success(petById);
        }else {
            return Result.error();
        }
    }
    /**
     * 根据id删除
     */
    @PostMapping("/delById/{id}")
    @ResponseBody
    public Result delById(@PathVariable Integer id) {
        System.out.println("ids = " + id);
        boolean i = petService.deleteById(id);
        if (i) {
            return Result.success();
        }
        return Result.error();
    }


    /**
     * 修改
     * @param aPet
     * @return
     */
    @PostMapping("/update")
    @ResponseBody
    public Result update(@RequestBody APet aPet) {
        System.out.println("aPet = " + aPet);
        int update = petService.update(aPet);
        if (update < 0) {
            return Result.error();
        }
        return Result.success();
    }
}
